package com.baizhi.service.impl;


import com.alibaba.druid.util.StringUtils;
import com.baizhi.dto.VideoDTO;
import com.baizhi.dto.VideoDetailDTO;
import com.baizhi.entity.Category;
import com.baizhi.entity.User;
import com.baizhi.entity.Video;
import com.baizhi.feign.CategoryClient;
import com.baizhi.feign.UserClient;
import com.baizhi.mapper.VideoMapper;
import com.baizhi.service.VideoService;
import com.baizhi.utils.JSONUtils;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 视频 服务实现类
 * </p>
 *
 * @author 2107class
 * @since 2021-12-22
 */
@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements VideoService {

    private static final Logger log = LoggerFactory.getLogger(VideoServiceImpl.class);
    @Autowired
    private VideoMapper videoMapper;

    @Autowired
    private UserClient userClient;

    @Autowired
    private CategoryClient categoryClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public List<Video> selectPage(Integer page, Integer perPage) {
        Page<Video> page1 = new Page<>(page,perPage);
        videoMapper.selectPage(page1,null);
        ValueOperations ops = redisTemplate.opsForValue();

        //设置点赞数
        Integer likes=5;

        //将点赞数存入redis中
        ops.set("likes",likes);

        List<Video> videos = page1.getRecords();
        for (Video video : videos) {
            //点赞数
            video.setLikes(likes);

            User user = userClient.selectOne(video.getUid());
            video.setUploader(user);
            Category category = categoryClient.selectOne(video.getCategoryId());
            video.setCategory(category.getName());
            System.out.println(video);
        }

        return videos;
    }

    /*@Override
    public Video add(MultipartFile file, String title, String intro, String categoryId,Integer uid) {

        long time = new Date().getTime();
        String fileName = time+file.getOriginalFilename();
        AliYun.uploadByBytes(file,"video/"+fileName);
        //将视频截帧 设置时间限制
        String s = AliYun.jqVideo("video/" + fileName);
        //将视频第一帧保存在阿里云中
        int i = fileName.lastIndexOf('.');
        String substring = fileName.substring(0, i);
        AliYun.URLupload(s,substring+".jpg");

        //数据入库
        Video video = new Video();
        video.setCover("http://2017class.oss-cn-beijing.aliyuncs.com/videoImg/"+substring+".jpg"); //封面路径
//        video.setCreatedAt(new Date());
        video.setLink("http://2017class.oss-cn-beijing.aliyuncs.com/video/"+fileName);
        videoMapper.insert(video);
        return video;
    }*/

    @Override
    public VideoDTO insert(Video video) {
        videoMapper.insert(video);
        //注意:利用MQ异步处理,提升系统响应: 将视频信息写入到ES索引库  1.在es中建立6.x  索引index  类型type   映射概念mapping   2.将视频信息写入es
        VideoDTO videoDTO = getVideoVO(video);
        rabbitTemplate.convertAndSend("videos", "", JSONUtils.writeValueAsString(videoDTO));
        return videoDTO;
    }


    //将list video 转为 list videoVO
    public List<VideoDTO> getList(List<Video> videos) {
        //创建VideoVo集合
        List<VideoDTO> videoDTOS = new ArrayList<>();
        //对video进行遍历 在遍历过程中转为videoVo
        videos.forEach(video -> {
            videoDTOS.add(getVideoVO(video));//添加视频
        });
        return videoDTOS;
    }

    //将 video 转为 videoVO
    public VideoDTO getVideoVO(Video video) {
        //创建VideoVo
        VideoDTO videoDTO = new VideoDTO();
        //复制属性
        BeanUtils.copyProperties(video, videoDTO);//复制属性  id title cover gmtCreate

        //视频服务----->调用用户服务 根据用户id查询用户
        User user = userClient.selectOne(video.getUid());//调用用户服务
        log.info("根据id查询用户信息为: {}", JSONUtils.writeValueAsString(video));
        videoDTO.setUploader(user.getName());//设置用户名

        //视频服务---->调用类别服务  根据类别id查询类别
        Category category = categoryClient.selectOne(video.getCategoryId());
        log.info("根据类别id查询到的类别信息为: {}", JSONUtils.writeValueAsString(category));
        videoDTO.setCategory(category.getName());

        //设置点赞数量
        videoDTO.setLikes(0);

        /*String counts = (String) stringRedisTemplate.opsForValue().get(video.getId());*/
       /* if (!StringUtils.isEmpty(counts)) {
            log.info("当前视频点赞数量为: {}", counts);
            videoDTO.setLikes(Integer.valueOf(counts));
        }*/
        return videoDTO;
    }

    /*@Override
    public VideoDTO insert(Video video) {
        videoMapper.insert(video);
        //注意:利用MQ异步处理,提升系统响应: 将视频信息写入到ES索引库  1.在es中建立6.x  索引index  类型type   映射概念mapping   2.将视频信息写入es
        VideoDTO videoDTO = getVideoDTO(video);
        rabbitTemplate.convertAndSend("videos", "", JSONUtils.writeValueAsString(videoDTO));
        return videoDTO;
    }*/







    @Override
    public VideoDetailDTO queryDetailById(Integer videoId, String token) {
        //1.根据id查询视频信息
        Video video = videoMapper.selectById(videoId);

        //2.创建videoDetailVo
        VideoDetailDTO videoDetailVO = new VideoDetailDTO();

        //3.将video对象中基本信息复制到VideoDetailVo {id title cover link created_at update_at}
        BeanUtils.copyProperties(video, videoDetailVO);

        //4.设置当前视频类别名称  VideoDetailVo {id title cover link created_at update_at category}
        Category category = categoryClient.selectOne(video.getCategoryId());//调用类别服务
        log.info("根据类别id查询到的类别信息为: {}", JSONUtils.writeValueAsString(category));
        videoDetailVO.setCategory(category.getName());


        //5.设置用户信息 VideoDetailVo {id title cover link created_at update_at category uploader}
        User user = userClient.selectOne(video.getUid());//调用用户服务
        log.info("根据id查询用户信息为: {}", JSONUtils.writeValueAsString(video));
        videoDetailVO.setUploader(user);

        //6.设置播放次数 {id title cover link created_at update_at category uploader plays_count}
        videoDetailVO.setPlaysCount(0);//初始化默认值为0

        String playedCounts = stringRedisTemplate.opsForValue().get(videoId);
        if (!StringUtils.isEmpty(playedCounts)) {
            log.info("当前视频视频播放次数为: {}", playedCounts);
            videoDetailVO.setPlaysCount(Integer.valueOf(playedCounts));
        }


        //7.设置点赞数 {id title cover link created_at update_at category uploader plays_count likes_count}
        videoDetailVO.setLikesCount(0);//初始化默认值为0
        String likedCounts = stringRedisTemplate.opsForValue().get(video.getId());
        if (!StringUtils.isEmpty(likedCounts)) {
            log.info("当前视频点赞数量为: {}", likedCounts);
            videoDetailVO.setLikesCount(Integer.valueOf(likedCounts));
        }


        //8.设置当前用户是否喜欢  不喜欢  收藏 {id title cover link created_at update_at category uploader plays_count likes_count liked  disabled favorite}
        User o = (User) redisTemplate.opsForValue().get("session_" + token);
        if (!ObjectUtils.isEmpty(o)) {
            //设置是否喜欢
            Boolean liked = redisTemplate.opsForSet().isMember(o.getId(), videoId);
            videoDetailVO.setLiked(liked);
            //设置是否不喜欢
            Boolean disliked = redisTemplate.opsForSet().isMember(o.getId(), videoId);
            videoDetailVO.setDisliked(disliked);
            //设置是否收藏
//            Favorite favorite = userClients.favorite(videoId, o.getId().toString());
//            log.info("是否收藏过该视频: {}", !ObjectUtils.isEmpty(favorite));
//            if (!ObjectUtils.isEmpty(favorite)) {
//                videoDetailVO.setFavorite(true);
//            }
        }

        return videoDetailVO;
    }





}
